package cn.yh.register.hosp.service.impl;

import cn.yh.register.hosp.repository.ScheduleRepository;
import cn.yh.register.hosp.service.ScheduleService;
import cn.yh.register.model.hosp.Schedule;
import cn.yh.register.vo.hosp.ScheduleQueryVo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    ScheduleRepository scheduleRepository;

    /**
     * 保存排班
     * @param objectMap 排班数据
     */
    @Override
    public void saveSchedule(Map<String, Object> objectMap) {
        //转对象
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(objectMap), Schedule.class);
        //先查询是否存在
        Schedule schedule1 = scheduleRepository.findByHoscodeAndDepcodeAndHosScheduleId(schedule.getHoscode(), schedule.getDepcode(), schedule.getHosScheduleId());
        if (schedule1 == null) {
            //不存在，新增
            schedule.setCreateTime(new Date());
            schedule.setIsDeleted(0);
        } else {
            //存在，修改
            schedule.setId(schedule1.getId());
            schedule.setCreateTime(schedule1.getCreateTime());
            schedule.setIsDeleted(schedule1.getIsDeleted());
        }
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }

    /**
     * 分页查询排班列表
     * @param pageNo   当前页码
     * @param pageSize 每页条数
     * @param queryVo  分页数据
     * @return
     */
    @Override
    public Page<Schedule> getScheduleList(Integer pageNo, Integer pageSize, ScheduleQueryVo queryVo) {
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(queryVo,schedule);
        //条件对象
        Example<Schedule> example = Example.of(schedule, ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true));
        //分页对象
        PageRequest pageRequest = PageRequest.of(pageNo-1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        //分页查修
        return scheduleRepository.findAll(example, pageRequest);


    }

    /**
     * 删除排班
     * @param hoscode       医院编号
     * @param hosScheduleId 排班编号
     */
    @Override
    public void removeSchedule(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.findByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (schedule!=null) {
            scheduleRepository.delete(schedule);
        }
    }
}
